
function bindEvent(ele, type, selector, fn) {
  if(!fn) {
    fn = selector
    selector = null
  }
  ele.addEventListener(type, function(event){
    const target = event.target
    if(selector){
      if(target.matches(selector)){
        fn.call(target, event)
      }
    }
    else {
      fn.call(target, event)
    }
  })
}

const btn1 = document.getElementById('btn1')
bindEvent(btn1, 'click', function(event){
  alert(this.innderHTML)
  event.preventDefault()
})

const body = document.body
bindEvent(body, 'click', function(event){
  console.log('取消')
})
const p1 = document.getElementById('p1')
bindEvent(p1, 'click', function(event){
  console.log('激活')
  event.stopPropagation() // 阻止冒泡
})

// const div2 = document.getElementById('div2')
// binEvent(div2, 'click', function(event){
//   console.log('div2 clicked')
//   console.log(event.target)
// })

const div3 = document.getElementById('div3')

bindEvent(div3, 'click', function(event){
  event.preventDefault()
  alert(this.innerHTML)
})